import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login/login.vue'
import home from '@/views/home/home.vue'
import find from '@/views/home/find/find.vue'
import my from '@/views/home/my/my.vue'
import question from '@/views/home/question/question.vue'
import info from '@/views/info/info.vue'
// 导入store
import store from '@/store/index.js'
// 导入local
import { localGet } from '@/utils/local.js'
// 导入Toast
import { Toast } from 'vant'
// 导入获取信息方法
import { apiGetInfo } from '@/api/au.js'
import editinfo from '@/views/info/editinfo.vue'
import editupload from '@/views/info/editupload.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },

  {
    path: '/login',
    component: login
  },
  {
    path: '/home',
    component: home,
    redirect: '/home/my',
    children: [
      { path: '/home/find', component: find },
      { path: '/home/my', component: my, meta: { needLogin: true } },
      { path: '/home/question', component: question, meta: { needLogin: true } }
    ]
  },
  { path: '/info', component: info, meta: { needLogin: true } },
  { path: '/editinfo', component: editinfo, meta: { needLogin: true } },
  { path: '/editupload', component: editupload, meta: { needLogin: true } }
]

const router = new VueRouter({
  routes
})
// 导入路由前置导航守卫
router.beforeEach(async (to, from, next) => {
  console.log(to)
  const needLogin = to.meta.needLogin
  if (!needLogin) {
    next()
  } else {
    if (localGet('token')) {
      const userInfo = store.state.userInfo
      if (userInfo) {
        next()
      } else {
        apiGetInfo().then(res => {
          res.data.avatar = 'http://localhost:1337' + res.data.avatar
          store.commit('setUserInfo', res.data)
        })
        next()
        // const res = await apiGetInfo()
        // res.data.avatar = 'http://localhost:1337' + res.data.avatar
        // store.commit('setUserInfo', res.data)
        // next()
      }
    } else {
      Toast.fail('请登录')
      next(`/login?_redirect=${to.fullPath}`)
      // router.push(`/login?_redirect=${to.fullPath}`)
    }
  }
})

export default router
